// 价格格式化函数
export const formatPrice = price => {
  if (typeof price !== 'number' && typeof price !== 'string') {
    return '¥0.00'
  }
  const numPrice = Number(price)
  if (isNaN(numPrice)) {
    return '¥0.00'
  }
  return `¥${numPrice.toFixed(2)}`
}

// 数组去重
export const uniqueArray = (array, key) => {
  if (!array || !Array.isArray(array)) {
    return []
  }
  if (key) {
    return array.filter((item, index, self) => index === self.findIndex(t => t[key] === item[key]))
  }
  return [...new Set(array)]
}

// 深度复制对象
export const deepClone = obj => {
  if (obj === null || typeof obj !== 'object') {
    return obj
  }
  if (obj instanceof Date) {
    return new Date(obj.getTime())
  }
  if (obj instanceof Array) {
    return obj.map(item => deepClone(item))
  }
  if (typeof obj === 'object') {
    const clonedObj = {}
    for (const key in obj) {
      if (Object.prototype.hasOwnProperty.call(obj, key)) {
        clonedObj[key] = deepClone(obj[key])
      }
    }
    return clonedObj
  }
  return obj
}

/**
 * 获取URL参数
 * @param {string} url - URL地址，默认为当前URL
 * @returns {Object} 解析后的参数对象
 */
export const getUrlParams = (url = window.location.href) => {
  const params = {}
  const queryString = url.split('?')[1]

  if (queryString) {
    const pairs = queryString.split('&')

    pairs.forEach(pair => {
      const [key, value] = pair.split('=')
      if (key) {
        params[decodeURIComponent(key)] = decodeURIComponent(value || '')
      }
    })
  }

  return params
}

// 防抖函数
export const debounce = (func, wait = 300) => {
  let timeout = null
  return function (...args) {
    const context = this
    if (timeout) clearTimeout(timeout)
    timeout = setTimeout(() => {
      func.apply(context, args)
    }, wait)
  }
}

// 节流函数
export const throttle = (func, delay = 300) => {
  let lastCall = 0
  return function (...args) {
    const now = new Date().getTime()
    if (now - lastCall < delay) {
      return
    }
    lastCall = now
    return func.apply(this, args)
  }
}

// 检查是否为移动端
export const isMobile = () => {
  return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
}

// 日期格式化
export const formatDate = (date, format = 'YYYY-MM-DD') => {
  const d = new Date(date)
  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  const hours = String(d.getHours()).padStart(2, '0')
  const minutes = String(d.getMinutes()).padStart(2, '0')
  const seconds = String(d.getSeconds()).padStart(2, '0')

  return format
    .replace('YYYY', year)
    .replace('MM', month)
    .replace('DD', day)
    .replace('HH', hours)
    .replace('mm', minutes)
    .replace('ss', seconds)
}

// 生成唯一ID
export const generateId = () => {
  return Date.now().toString(36) + Math.random().toString(36).substr(2)
}

// 计算两个日期之间的天数
export const daysBetween = (date1, date2) => {
  const timeDiff = Math.abs(new Date(date2) - new Date(date1))
  return Math.ceil(timeDiff / (1000 * 3600 * 24))
}
